/**
 * this files imports or updates exisiting entries with pubchem compound properties
 */

import org.apache.log4j.Logger

import edu.ucdavis.genomics.metabolomics.binbase.connector.references.lipidmaps.LipidMapsSDFContentResolver
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.InchFinder
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.SdfToInchi

//configuration file
def config = new ConfigSlurper().parse(new File('grails-app/conf/PathConfiguration.groovy').toURL())

Logger logger = Logger.getLogger("Import Lipid Maps")

logger.info("starting import/update of the pubchem compound data")


String tempDir = config.files.lipidmaps.rawdata

FileHelper.workOnDir(tempDir, {File file ->
  LipidMapSubstance sub = new LipidMapSubstance()
  SdfToInchi.sdfToInchi(new FileInputStream(file), sub)

}, logger, ".sdf")

class LipidMapSubstance implements InchFinder {
  public void foundInchi(String myInchi, Map<java.lang.Object, java.lang.Object> objectObjectMap) throws Exception {

    Logger logger = Logger.getLogger("Import Lipid Maps")

    LipidMapsSDFContentResolver resolver = new LipidMapsSDFContentResolver();

    resolver.prepare(objectObjectMap)

    //logger.debug "loading compound from library ${resolver.getInchi()}"
    Compound compound = CompoundHelper.getCompound(resolver.getInchi(), resolver.getInchiKey(), logger)

    //saves the pubchem id
    if (resolver.getPubchemSID() != null) {
      CompoundHelper.updateSID(logger, compound, Integer.parseInt(resolver.getPubchemSID()))
    }

    CompoundHelper.updateLipidMaps(logger, compound, resolver.getLipidmapsId())

    //sets the comound properties
    setCompoundProperties(resolver, compound)

    if (resolver.getSystematicName() != null) {
      //work on iupac names
      List<String> iupacs = new Vector<String>()

      iupacs.add(resolver.getSystematicName())

      CompoundHelper.updateIUPACNames(iupacs, compound, logger)
      CompoundHelper.addSynonym(iupacs, logger, compound)

    }

    if (resolver.getCommonName() != null) {
      //work on iupac names
      List<String> iupacs = new Vector<String>()

      iupacs.add(resolver.getSystematicName())

      CompoundHelper.addSynonym(iupacs, logger, compound)
    }

    //save our compound
    compound = CompoundHelper.saveCompound(compound, logger)

    CompoundHelper.aquireStatistic()
  }

  private def setCompoundProperties(LipidMapsSDFContentResolver resolver, Compound compound) {
    Double exactMass = resolver.getExactMass()
    String molecularFormula = resolver.getFormula();

    if (exactMass != null) {
      if (exactMass > 0) {
        compound.exactMolareMass = exactMass
      }
    }
    if (molecularFormula != null) {
      compound.formula = molecularFormula
    }
  }
}